<template>
    <div class="payBntBoxFordg" @click="openDailog">
        <slot/>
        <!---选择支付货币-->
        <my-dailog v-model:show="showFlag2" :showtopclose="true" :styleType="4" width="75%" height="80%">
            <div class="currencyBox">
                <div class="selectItem" v-if="detail.apiShopDetailDto.shopId">
                    <div class="bhTitle">ETH Chain</div>
                    <ul class="hbList">
                        <li @click="bhComfirm('ETH','ETH')" v-if="detail.apiShopDetailDto.payCurrency.indexOf('ETH')>-1">
                            <img src="/images/bicon1.png" alt=""/>
                            <span>ETH</span>
                            <em>{{banns.ethChain.eth}}</em>
                        </li>
                        <li v-else class="disabled">
                            <img src="/images/bicon1.png" alt=""/>
                            <span>ETH</span>
                            <em>{{banns.ethChain.eth}}</em>
                        </li>

                        <li @click="bhComfirm('USDT','ETH')" v-if="detail.apiShopDetailDto.payCurrency.indexOf('USDT')>-1">
                            <img src="/images/bicon2.png" alt=""/>
                            <span>USDT</span>
                            <em>{{banns.ethChain.usdt}}</em>
                        </li>
                        <li v-else class="disabled">
                            <img src="/images/bicon2.png" alt=""/>
                            <span>USDT</span>
                            <em>{{banns.ethChain.usdt}}</em>
                        </li>

                        <li @click="bhComfirm('CXT','ETH')" v-if="detail.apiShopDetailDto.payCurrency.indexOf('CXT')>-1">
                            <img src="/images/bicon3.png" alt=""/>
                            <span>CXT</span>
                            <em>{{banns.ethChain.ethCxt}}</em>
                        </li>
                        <li v-else class="disabled">
                            <img src="/images/bicon3.png" alt=""/>
                            <span>CXT</span>
                            <em>{{banns.ethChain.ethCxt}}</em>
                        </li>
                    </ul>
                </div>
                <div class="fg"></div>
                <div class="selectItem">
                    <div class="bhTitle">CXT Chain</div>
                    <ul class="hbList">
                        <li @click="bhComfirm('CXT','CXT')" v-if="detail.apiShopDetailDto.payCurrency.indexOf('CXT')>-1">
                            <img src="/images/bicon4.png" alt=""/>
                            <span>CTX</span>
                            <em>{{banns.cxtChain.cxt}}</em>
                        </li>
                        <li v-else class="disabled">
                            <img src="/images/bicon4.png" alt=""/>
                            <span>CTX</span>
                            <em>{{banns.cxtChain.cxt}}</em>
                        </li>
                    </ul>
                </div>
            </div>
        </my-dailog>
        <!--/选择支付货币--->

        <!--配送方式：自提、送货-->
        <my-dailog v-model:show="showFlag3" :showtopclose="true" :styleType="2" height="auto">
            <div class="pstypeBox">
                <div class="mbzf-btnBox">
                    <my-button :text="text11" @click="goOrder(2)"/>
                </div>
                <div class="mbzf-btnBox">
                    <my-button :text="text12" @click="goOrder(1)"/>
                </div>
            </div>
        </my-dailog>
        <!-- /配送方式：自提、送货 -->

        <!---支付密码-->
        <my-dailog v-model:show="showFlag1" :showtopclose="true" :styleType="2">
            <div class="payDgBox">
                <div class="iconBox">
                    <i class="iconfont icon-zhuyi-yin"></i>
                    <p v-t="'goods.text13'">Please enter the metado password to complete the payment</p>
                </div>
                <div class="inputbox">
                    <input type="password" v-model="pass"/>
                </div>
                <div class="mbzf-btnBox">
                    <my-button text="Confirm" @click="paySubmit"/>
                </div>
            </div>
        </my-dailog>
        <!-- /支付密码 -->
    </div>
</template>

<script>
import { reactive,toRefs,getCurrentInstance,computed,onMounted } from 'vue'
import {useRoute,useRouter} from 'vue-router'
import { useStore } from 'vuex'
import myDailog from '@/components/myDailog.vue'
import myButton from '@/components/myButton.vue';
import { toast,H5CallAPPFuction } from '@/utils/common';
import returnGoodsVue from '../views/shop/coupons/detail/components/returnGoods.vue';
import { useI18n } from 'vue-i18n'

export default {
    components:{
       myDailog,
       myButton
    },
    props:{
        type:{  // 1为详情页操作按钮，需要选择货币类型和取货方式，2支付，直接弹出输入支付密码
            type:Number,
            default:1
        },
        couponId:{ 
            type:String,
            default:null
        }
    },
    setup(props,context){
        const router = useRouter()
        const route = useRoute()
        const store = useStore()
        const {proxy} = getCurrentInstance()
        const {t} = useI18n()

        const state = reactive({
            userInfo:computed(()=>store.state.base.userInfo),
            showFlag1:false,
            showFlag2:false,
            showFlag3:false,
            pass:'',
            detail:computed(()=>store.state.shop.detail),
            orderInfo:computed(()=>store.state.shop.orderInfo),
            curAddress:computed(()=>store.state.shop.curAddress), // 当前当前选择的地址
            banns:{
                cxtChain:{
                    cxt:'0.00'
                },
                ethChain:{
                    eth:'0.00',
                    usdt:'0.00',
                    ethCxt:'0.00'
                }
            },
             text11:t('goods.text11'),//'Self withdrawal'
             text12:t('goods.text12'),//'Home Delivery'
        })

        onMounted(()=>{
            // App调用，获取ethChain的余额
            window['walletBalance'] = function (objStr) {
                state.banns.ethChain = JSON.parse(objStr)
            }
            // 定义tradeResults方法，供app调用(app交易处理完成后调用)
            window['tradeResults'] = function (result) { // result：{"success":0,"msg":""}
                if(!result){
                    return toast('No Processing Result') // 没有处理结果
                }
                const rt = JSON.parse(result)
                if(rt.success==0){ // 支付处理出错了
                    toast(rt.msg)
                }else{
                    toast('Purchase Succeeded！')
                    setTimeout(()=>{
                        router.push('/collection/number')
                    },2000)
                } 
            }

            try {
                H5CallAPPFuction('jsLoadComplete')  // 调用app的jsLoadComplete方法,通知app，H5页面加载了
                H5CallAPPFuction('getWalletBalance')  // 调用app的getWalletBalance方法,通知app条用H5的walletBalance方法，获取钱包余额，
            } catch (error) {
                console.log("调用app的jsLoadComplete出错了：不是在app环境中调用")
            }


            // 获取CXT Chain的CXT资产余额
            store.dispatch('capital/get_my_assets',{
                walletAddress:state.userInfo.walletAddress
            }).then(res=>{
                state.banns.cxtChain.cxt = res.data.cxtAvailableAmount.decimalTwoString
            })

            //store.dispatch('shop/create_order')
        })

        const openDailog = ()=>{
            if(state.detail.specs && state.detail.specs.length>0 && !state.orderInfo.specs.specName){
                return toast(t('goods.tip1'))
            }
            // else if(!state.orderInfo.params.paramValue){
            //     return toast('请选择商品参数')
            // }
            //数字商品直接支付
            if(state.detail.goodsType==6){
                if(state.orderInfo.chainType==''||state.orderInfo.chainType==null){
                    state.showFlag2=true
                    return
                }
                 store.dispatch('shop/create_number_order',{
                        shopCouponId:props.couponId,
                        walletAddress:state.userInfo.walletAddress,
                        logisticsType:2
                    }).then(res =>{
                        if(res.success){
                            // 调用app方法
                            try {
                                //订单创建成功后，交由app处理支付相关逻辑，H5只接受处理结果（tradeResults方法接收）
                                const appParams = {
                                    orderId:res.data.orderId,
                                    chainType:state.orderInfo.chainType,
                                    currency:state.orderInfo.currency,
                                    chainTotalAmount:res.data.chainTotalAmount.num,
                                    orderNo:res.data.orderNo,
                                    payOrderNo:res.data.payOrderNo,
                                    contractAddress:res.data.contractAddress,
                                    toAddress:res.data.toAddress,
                                    inStore:'0',
                                    goodsType:1 //1-数字商品，2-实物商品 给APP值
                                }
                                console.log("appParams:",appParams)
                                H5CallAPPFuction('buyGoods',JSON.stringify(appParams)) 
                            } catch (error) {
                                toast('调用app失败')
                                // setTimeout(()=>{
                                //     tradeResults('{"success":0,"msg":""}')
                                // },3000) 
                            }
                        }else{ // 创建订单失败
                            return toast(res.message)
                        }
                    })
                return
            }
            if(props.type==2){ //订单界面的操作按钮，直接弹出输入支付密码
                if(state.orderInfo.logisticsType==2){ // 自提
                    if(!state.orderInfo.selfAddress){
                        return toast(t('goods.tip2')) //toast('Please Select The Self Delivery Address!')
                    }
                }else{ // 物流配送
                    if(!state.curAddress.userShippingAddressId){
                        return toast(t('goods.tip3')) //return toast('Please Select Receipt Information!')
                    }
                }
                paySubmit()  // H5不弹窗支付密码，直接调用app（app处理支付密码等）
                //state.showFlag1 = true // 弹出支付密码
            }else{ // 详情页操作按钮进来的，需选择货币类型和配送方式
                // 判断是否需要选择货币
                if(state.detail.apiShopDetailDto.payCurrency=='ETH' || state.detail.apiShopDetailDto.payCurrency=='USDT'){// 无需选择货币
                    store.commit('shop/set_orderInfo',{
                        currency:state.detail.apiShopDetailDto.payCurrency,
                        chainType:'ETH'
                    })
                    // 判读是否需要选择配送方式
                    checkDeliveryType()
                }else{ // 需要选择货币 goodsChannel 商品发布渠道范围 1 店铺 2 预售 跳转到原生
                    if(state.detail.goodsChannel==1){
                        state.showFlag2 = true
                    }else{
                          checkDeliveryType() // 配送方式判断
                    }
                    
                }
                 
            }
        }
        // 检查配送方式：送货、自提
        const checkDeliveryType = ()=>{
            if(state.detail.apiShopDetailDto.logisticsDeliveryStatus==1 && state.detail.apiShopDetailDto.logisticsSelfStatus==1){
                // 配送方式为：送货和自提，需要弹窗选择
                state.showFlag3 = true
            }else if(state.detail.apiShopDetailDto.logisticsDeliveryStatus==1){
                goOrder(1) // 跳转到送货订单页面
            }else if(state.detail.apiShopDetailDto.logisticsSelfStatus==1){
                goOrder(2) // 跳转到自提订单页面
            }
        }
        const bhComfirm = (currency,chainType)=>{
            store.commit('shop/set_orderInfo',{
                currency,
                chainType
            })
            state.showFlag2 = false
            //state.showFlag3 = true
             if(state.detail.goodsType!=6){
                checkDeliveryType() // 配送方式判断
             }
        }
        const goOrder = (num)=>{
            store.commit('shop/set_orderInfo',{
                logisticsType:num
            })
            console.log("orderInfo3:",state.orderInfo)
            if(num==2){ // 1:物流送货，2:自提
                router.push('/shop/self')
            }else{
                router.push('/shop/delivery')
            }
        }
        

        const paySubmit = ()=>{
                 if(state.detail.goodsChannel==2){ //goodsChannel 商品发布渠道范围 1 店铺 2 预售 跳转到原生
                        let baseParams ={
                            chainType:state.orderInfo.chainType,
                            currency:state.orderInfo.currency,
                            goodsAttr:state.orderInfo.specs.specGroupName+"|"+state.orderInfo.specs.specName,
                            goodsId:state.orderInfo.goodsId,
                            quantity:state.orderInfo.quantity,
                            logisticsType:state.orderInfo.logisticsType,
                            walletAddress:state.userInfo.walletAddress,
                            inStore:'0',
                            goodsType:2 //1-数字商品，2-实物商品 给APP值
                        }
                        if(state.orderInfo.logisticsType==2){ // 自提
                            let selfParams ={
                                logisticsSelfAddress:state.orderInfo.selfAddress.split("|")[0],
                                logisticsSelfPhone:state.orderInfo.selfAddress.split("|")[1],
                                inStore:"1"
                            }
                            Object.assign(baseParams,selfParams)
                        }else{ // 物流配送
                            let deliveryParams ={
                                logisticsDeliveryCityId:state.curAddress.cityId,	//物流送货城市id
                                logisticsDeliveryCityName:state.curAddress.cityName,	//物流送货城市名称	
                                logisticsDeliveryCountryId:state.curAddress.countryId,	//物流送货国家ID
                                logisticsDeliveryCountryName:state.curAddress.countryName,	//物流送货国家名称
                                shippingAddress:state.curAddress.address,// 收货地址
                                shippingName:state.curAddress.name, // 收货人姓名
                                shippingPhone:state.curAddress.phone, // 收货人联系电话
                                inStore:state.orderInfo.logisticsType==2?'1':'2' //（inStore），1为自提，2为物流，0为无需物流或者自提，
                            }
                            Object.assign(baseParams,deliveryParams)
                        }
                        try {
                            H5CallAPPFuction('buyGoods',JSON.stringify(Object.assign(baseParams))) 
                        } catch (error) {
                            toast('调用app失败')
                        }
               }else{
                store.dispatch('shop/create_order',{
                        shopCouponId:props.couponId,
                        walletAddress:state.userInfo.walletAddress
                    }).then(res =>{
                        if(res.success){
                            //toast('Order payment completed')
                            // 调用app方法
                            try {
                                //订单创建成功后，交由app处理支付相关逻辑，H5只接受处理结果（tradeResults方法接收）
                                const appParams = {
                                    orderId:res.data.orderId,
                                    chainType:state.orderInfo.chainType,
                                    currency:state.orderInfo.currency,
                                    chainTotalAmount:res.data.chainTotalAmount.num,
                                    orderNo:res.data.orderNo,
                                    payOrderNo:res.data.payOrderNo,
                                    contractAddress:res.data.contractAddress,
                                    toAddress:res.data.toAddress,
                                    inStore:state.orderInfo.logisticsType==2?'1':'2', //（inStore），1为自提，2为物流，0为无需物流或者自提，
                                    goodsType:2 //1-数字商品，2-实物商品 给APP值
                                }
                                console.log("appParams:",appParams)
                                H5CallAPPFuction('buyGoods',JSON.stringify(appParams)) 
                            } catch (error) {
                                toast('调用app失败')
                                // setTimeout(()=>{
                                //     tradeResults('{"success":0,"msg":""}')
                                // },3000) 
                            }
                        }else{ // 创建订单失败
                            return toast(res.message)
                        }
                    })
                     context.emit('confirm',state.pass)
                 }
           
        }

        return{
            ...toRefs(state),
            openDailog,
            bhComfirm,
            goOrder,
            paySubmit
        }
    }
}
</script>

<style lang="scss" scoped>
    .payBntBoxFordg{
        width: 100%;
        height: 100%;
    }
    .payDgBox{
        .iconBox{
            text-align: center;
            i{
                font-size: 130px;
                color: #49B4D2;
            }
            p{
                padding: 0 30px;
                line-height: 42px;
                font-family: Inter-Medium, Inter;
                font-weight: 500;
                color: #FFFFFF;
                font-size: 32px;
                margin: -10px 0 0 0;
            }
        }
        .inputbox{
            text-align: center;
            padding: 30px 0 0 0;
            input{
                height: 80px;
                line-height: normal;
                width: 90%;
                background: rgba(103,248,255,0.2000);
                border: 1px solid rgba(103,248,255,0.5000);
                padding: 0 30px;
            }
        }
        .mbzf-btnBox{
            width: 400px;
            margin: 50px auto 0 auto;
        }
    }
    .currencyBox{
        display: flex;
        width: 100%;
        height: 100%;
        padding: 5px 60px 0 0;
        .selectItem{
            display: flex;
            flex-flow: column;
            flex: 1;
            background: url(/images/detail/hb.png) left top no-repeat;
            background-size: 100% 100%;
            padding: 30px;
            .bhTitle{
                font-family: Poppins-SemiBold, Poppins;
                font-weight: 600;
                color: #FFFFFF;
                font-size: 32px;
                text-align: center;
                line-height: normal;
                padding: 10px 0;
            }
            .hbList{
                flex: 1;
                overflow: hidden;
                overflow-y: auto;
                li{
                    display: flex;
                    height: 90px;
                    align-items: center;
                    background: url(/images/detail/hb2.png) left top no-repeat;
                    background-size: 100% 100%;
                    padding: 0 20px;
                    font-size: 30px;
                    font-family: Poppins-SemiBold, Poppins;
                    font-weight: 600;
                    color: #FFFFFF;
                    &.disabled{
                        opacity: 0.2;
                    }
                    &+li{
                        margin: 20px 0 0 0;
                    }
                    img{
                        width: 30px;
                    }
                    span{
                        flex: 1;
                        padding: 0 0 0 30px;
                    }
                    em{
                        font-style: normal;

                    }
                }
            }
        }
        .fg{
            width: 20px;
        }
    }
    .pstypeBox{
        display: flex;
        flex-flow: column;
        width: 100%;
        height: 100%;
        align-items: center;
        justify-content: center;
        padding:100px 40px;
        .mbzf-btnBox{
            width: 100%;
            height: 80px;
            .myBtn{
                height: 100%;
                line-height: 80px;
            }
            &+.mbzf-btnBox{
                margin: 40px 0 0 0;
            }
        }
    }
</style>